package br.com.traffic.help.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	
	private static final SessionFactory factory;
	private static final ServiceRegistry serviceRegistry;


	static{
		Configuration config = getConfiguration();
		
		serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
		
		config.setSessionFactoryObserver(new SessionFactoryObserver(){
			@Override
			public void sessionFactoryCreated(SessionFactory factory){}
			@Override
			public void sessionFactoryClosed(SessionFactory factory){
				ServiceRegistryBuilder.destroy(serviceRegistry);
			}
		});
		
		factory = config.buildSessionFactory(serviceRegistry);
	}
	

	
	private static Configuration getConfiguration(){
		Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
		return cfg;
	}

	public static Session openSession(){
		return factory.openSession();
	}
	
}
